from pathlib import Path

from PIL import Image
import cv2

# from anoDetection import detect_inference
# from anoInversion import inversion_inference
# from data.process import preprocess
# from Inversion import inversion
import pymysql
import pymysql.cursors
import time


db_config = {
    "host": "localhost",
    "user": "root",
    "password": "123456",
    "db": "digital_twin_local",
}


def connect_to_database():
    connection = pymysql.connect(cursorclass=pymysql.cursors.DictCursor, **db_config)
    return connection


def select_unchecked_image_data():
    connection = connect_to_database()
    try:
        with connection.cursor() as cursor:
            sql = "select timetamp, folder_name, img_path, format from tb_image where checked = 0"
            print(sql)
            cursor.execute(sql)
            result = cursor.fetchall()
            connection.close()
            return result
    finally:
        # 注意：这里不关闭连接，保持连接的唯一性
        pass


def select_unchecked_text_data():
    connection = connect_to_database()
    try:
        with connection.cursor() as cursor:
            # sql = "select temperature, humidity, air_pressure, wind_speed,wind_direction, total_cloud, flew_cloud, " \
            #       "cloud_form, visibility, precipitation, timetamp, bv, swd, swu, lwd, lwu, ts, sd, pt " \
            #       "from tb_text where checked = 0"
            sql = "select * from tb_text where checked = 0"
            print(sql)
            cursor.execute(sql)
            result = cursor.fetchall()
            connection.close()
            return result
    finally:
        # 注意：这里不关闭连接，保持连接的唯一性
        pass


def create_report():
    connection = connect_to_database()

    try:
        with connection.cursor() as cursor:
            sql = "select * from tb_result ORDER BY timetamp ASC LIMIT 1"
            print(sql)
            cursor.execute(sql)
            result_list = cursor.fetchall()
            connection.close()
    finally:
        # 注意：这里不关闭连接，保持连接的唯一性
        pass

    result = result_list[0]
    print(result)
    print(result_list)
    if int(result.get('detect_label')) == 0:
        detect_label_report = '图像受环境干扰因素较小，环境干扰指数为%s。' % (result.get('detect_score'))
        detect_report = detect_label_report
    else:
        detect_label_report = '图像受环境干扰因素较大，环境干扰指数为%s。' % (result.get('detect_score'))
        if float(result.get('detect_score')) > 80:
            detect_score_report = '。此时图像受环境干扰情况严重，图像拍摄效果较差，建议弃用。'
            detect_report = detect_label_report + detect_score_report
        elif float(result.get('detect_score')) < 80:
            detect_score_report = '。此时图像受环境干扰情况较重，图像拍摄效果受到影响，检测效果与实际结果存在一定误差，建议谨慎使用。'
            detect_report = detect_label_report + detect_score_report

    if int(result.get('inversion_score')) == -1:
        inversion_score_report = '此时拍摄图像强度较弱，不适用于使用反演算法计算反演温度，可能存在以下问题的可能：' \
                                 '1.此时图像与暗噪声图像不适配；2.提取背景杂散光出现问题。建议调整人工调整算法参数计算反演温度，' \
                                 '或重新拍摄暗噪声图像与现图像匹配。'
    else:
        inversion_score_report = '此时反演算法计算的反演温度为%s。' % (result.get('inversion_score'))

    report = '此结果生成时间为%s，该时刻' % (result.get('timetamp')) + detect_report + inversion_score_report + '该时刻' \
                                                                                                               '的图像受环境干扰结果图，转动温度光谱预处理后图像，预测图像分别保存在%s，%s，%s。' \
             % (result.get('detect_image'), result.get('spectrogram8'), result.get('generation_image'))

    return report


if __name__ == '__main__':
    # img_result = select_unchecked_image_data()

    # for i in range(len(img_result)):
    #     folder_name = img_result[i]['folder_name']
    #     img_path = img_result[i]['img_path']
    #     img_format = img_result[i]['format']
    #
    #     img_input = 'data/spectrogram/%s/%s.%s' % (folder_name, img_path, img_format)
    #     print(img_input)
    #     BG_input = 'data/spectrogram/%s/BG_dark_1.%s' % (folder_name, img_format)
    #     print(BG_input)
    #     preprocess.process(folder_name, img_path, img_format)
    #     img8_input, img16_input = preprocess.process(folder_name, img_path, img_format)
    #     print(img8_input, img16_input)
    #
    #     detect_image = "./detect_results/mdata/spectrogram8/%s/%s.png" % (folder_name, img_path)
    #     print(detect_image)

    # text_result = select_unchecked_text_data()
    # print(text_result[0])
    # for i in range(len(text_result)):
    #     prompt = {', '.join(f"'{key}': '{text_result[i].get(key)}'" for key in text_result[i])}
    #     print(type(prompt))

        # temperature = text_result[i]['temperature']
        # humidity = text_result[i]['humidity']
        # air_pressure = text_result[i]['air_pressure']
        # wind_speed = text_result[i]['wind_speed']
        # wind_direction = text_result[i]['wind_direction']
        # total_cloud = text_result[i]['total_cloud']
        # flew_cloud = text_result[i]['flew_cloud']
        # cloud_form = text_result[i]['cloud_form']
        # visibility = text_result[i]['visibility']
        # precipitation = text_result[i]['precipitation']
        # timetamp = text_result[i]['timetamp'] #.strftime('%Y-%m-%d %H:%M:%S')
        # bv = text_result[i]['bv']
        # swd = text_result[i]['swd']
        # swu = text_result[i]['swu']
        # lwd = text_result[i]['lwd']
        # lwu = text_result[i]['lwu']
        # ts = text_result[i]['ts']
        # sd = text_result[i]['sd']
        # pt = text_result[i]['pt']
        # # checked = text_result[i]['checked']
        # prompt = "temperature: " + str(temperature) + ", humidity: " + str(humidity) + ", air_pressure: " \
        #          + str(air_pressure) + ", wind_speed: " + str(wind_speed) + ", wind_direction: " \
        #          + str(wind_direction) + ", total_cloud: " + str(total_cloud) + ", flew_cloud: " + str(flew_cloud) \
        #          + ", cloud_form: n" + str(cloud_form) + ", visibility: " + str(visibility) + ", precipitation: " \
        #          + str(precipitation) + ", time: " + str(timetamp) + ", bv: " + str(bv) + ", swd: " + str(swd) \
        #          + ", swu: " + str(swu) + ", lwd: " + str(lwd) + ", lwu: " + str(lwu) + ", ts: " + str(ts) \
        #          + ", sd: " + str(sd) + ", pt: " + str(pt)
        #
        # print(prompt)
    img_bg = Image.open("D:\\GravityBrainSys\\static\\generation_results\\BG_image\\BG_dark_1.png")
    img_bg.resize((256, 256))
    img_bg.save("D:\\GravityBrainSys\\static\\generation_results\\BG_image\\BG_dark_1.png")

